package com.网络编程.net.http;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/5/22 下午3:43
 */
public class HttpPostJsonByURL {
    public static void main(String[] args) {
        try {
            String url = "https://api.example.com/post";
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            String jsonData = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(jsonData);
            out.flush();
            out.close();

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
